<script setup lang="tsx">
import { ref, inject } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { CheckIcon, CloseIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { getList, edit, getDictionaries } from '@/api/task/taskOrder';
import { getName } from '@/utils/tool';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 50,
    checkProps: ({ row }: { row: any }) => ({ disabled: row.status != 2 }),
  },
  {
    title: '订单ID',
    colKey: 'orderNumber',
    width: 120,
  },
  {
    title: '用户名',
    colKey: 'username',
  },
  {
    title: '风险账户',
    colKey: 'danger',
  },
  {
    title: '任务ID',
    colKey: 'taskId',
  },
  {
    title: '任务问题',
    colKey: 'question',
  },
  {
    title: '佣金',
    colKey: 'unitPrice',
  },
  {
    title: '任务等级',
    colKey: 'taskLevel',
  },
  {
    title: '当前状态',
    colKey: 'status',
  },
  {
    title: '领取时间',
    colKey: 'createTime',
  },
  {
    title: '提交时间',
    colKey: 'submitTime',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  taskId: string | null;
  taskLevel: string | null;
  username: string | null;
  danger: string | number | null;
  status: string | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  taskId: undefined,
  taskLevel: undefined,
  username: undefined,
  danger: undefined,
  status: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);

// 等级列表
import { useGradeStore } from '@/store/modules/member';
const gradeStore = useGradeStore();
const gradeList = ref<any[]>([]);
gradeList.value = gradeStore.gradeList;

// 状态列表
const typeList = ref([]);
const unGetTypeList = async () => {
  try {
    const res = await getDictionaries({});
    typeList.value = res.data;
  } catch (e) {
    console.log(e);
  }
};
unGetTypeList();

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <CheckIcon />} onClick={() => changeType(deleteId.value, '3')}>
        批量完成
      </t-button>
      <t-button theme="danger" icon={() => <CloseIcon />} onClick={() => changeType(deleteId.value, '4')}>
        批量失败
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.username} placeholder="用户名" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.taskId} placeholder="任务ID" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.taskLevel} placeholder="任务等级">
        {gradeList.value?.map((item) => (
          <t-option key={item.grade.toString()} label={item.name} value={item.grade.toString()} />
        ))}
      </t-select>
      <t-date-range-picker v-model={dateRange.value} placeholder="领取时间" />
      <t-select v-model={queryForm.value.status} placeholder="状态">
        {typeList.value?.map((item) => <t-option key={item.dictValue} label={item.dictLabel} value={item.dictValue} />)}
      </t-select>
      <t-select v-model={queryForm.value.danger} placeholder="风险账户">
        <t-option key={1} label="是" value={1} />
        <t-option key={0} label="否" value={0} />
      </t-select>
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="mtId"
      onUnGetList={unGetList}
    >
      {{
        danger: (slotProps: any) => (
          <div
            style={{
              color: slotProps.row.danger == 1 ? 'red' : '',
            }}
          >
            {slotProps.row.danger == 1 ? '是' : '否'}
          </div>
        ),
        unitPrice: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.unitPrice,
            )}
          </div>
        ),
        status: (slotProps: any) => (
          <div>{getName('dictValue', slotProps.row.status, typeList.value, 'dictLabel')}</div>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};
unGetList();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  dateRange.value = [];
  unGetList();
};

/** 对话框 */
const header = ref('确认通过当前所选订单？');
const body = ref('点击后将通过所选订单，是否继续？');
const type = ref('1');

// 不通过
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let mtIds = deleteId.value;
  let status = type.value;
  // type 3 通过 4 不通过
  edit({ mtIds, status }).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('操作成功');
    deleteId.value = [];
    unGetList();
  });
};

const changeType = (value: any, onType: string) => {
  if (!value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  const confirmText = onType == '3' ? '通过' : '不通过';
  header.value = `确认${confirmText}当前所选订单？`;
  body.value = `点击后将${confirmText}所选订单，是否继续？`;
  type.value = onType;
  confirmVisible.value = true;
  deleteId.value = value;
};
</script>

<template>
  <div>
    <render />
    <t-dialog v-model:visible="confirmVisible" :header="header" :body="body" @confirm="onConfirmDelete" />
  </div>
</template>
